<?php

namespace backend\modules\languages\controllers;

use Yii;
use yii\web\Controller;
use yii\helpers\VarDumper;
use yii\helpers\FileHelper;
use yii\filters\VerbFilter;
use backend\models\Clients;
use backend\modules\languages\models\Languages;
use backend\modules\languages\models\form\Filter;
use backend\modules\languages\models\form\Overrides;
use backend\modules\languages\models\Overrides as OverridesModel;

class OverridesController extends Controller
{
    /**
     *
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'delete' => [
                        'POST'
                    ]
                ]
            ]
        ];
    }

    /**
     * 文本替换列表
     *
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new Filter();
        $dataProvider = $searchModel->search(Yii::$app->request->bodyParams);

        $languageList = Languages::getList(['' => Yii::t('mod_langs', 'SELECT_LANGUAGE')], 'code', 'title');
        $clientArr = Clients::getList(['' => Yii::t('mod_langs', 'SELECT_CLIENT')]);
        $clientList = array_map(function ($client) {
            return ucfirst($client);
        }, $clientArr);

        return $this->render('index', [
            'model' => $searchModel,
            'dataProvider' => $dataProvider,
            'languageList' => $languageList,
            'clientList' => $clientList
        ]);
    }

    /**
     * 新增文本替换
     *
     * @return mixed
     * @throws yii\base\Exception
     */
    public function actionCreate()
    {
        $model = new Overrides();
        $request = Yii::$app->request;
        if ($request->isPost && $model->load($request->post())) {
            $client = Clients::findOne($model->client);
            $path = Yii::getAlias('@' . $client->name) . '/messages/overrides/';
            $fileName = $model->language . '.' . $model->category . '.override.php';
            $file = $path . $fileName;
            if (is_file($file)) {
                $data = include_once $file;
            }
            $data[$model->source_language] = $model->translate;
            FileHelper::createDirectory(dirname($file));
            $content = '<?php' . PHP_EOL . PHP_EOL . 'return ' . VarDumper::export($data) . ';' . PHP_EOL;
            file_put_contents($file, $content, LOCK_EX);
            Yii::$app->cache->delete('overrides');
            $overridesModel = new OverridesModel();
            $overridesModel->edit($model->category, $model->source_language, $model->translate, $model->language, $client->id, 1);
            return $this->redirect(['index']);
        }

        $filter = new Filter();
        if (empty($filter->language) || empty($filter->client)){
            Yii::$app->session->setFlash('warning', Yii::t('mod_langs', 'OVERRIDE_FIRST_SELECT_MESSAGE'));
            return $this->redirect(['index']);
        }

        $model->language = $filter->language;
        $model->client = $filter->client;

        $language = Languages::findOne(['code' => $filter->language]);
        $languageShow = $language->title . ' [' . $language->code . ']';
        $client = Clients::findOne($filter->client);
        $clientShow = ucfirst($client->name);

        return $this->render('create', [
            'model' => $model,
            'languageShow' => $languageShow,
            'clientShow' => $clientShow
        ]);
    }

    /**
     * 更新文本替换
     * @param string $id
     * @return mixed
     * @throws yii\base\Exception
     */
    public function actionUpdate($id)
    {
        $model = new Overrides();

        $request = Yii::$app->request;

        $overrides = Yii::$app->cache->get('overrides');
        $filter = null;
        foreach ($overrides as $item) {
            if ($item['id'] == $id) {
                $item['source_language'] = $item['key'];
                $item['translate'] = $item['value'];
                $filter = $item;
                break;
            }
        }

        if (is_null($filter)) {
            Yii::$app->session->setFlash('error', Yii::t('mod_langs', 'OVERRIDE_FIELD_KEY_NOT_EXIST'));
            return $this->redirect(['index']);
        }

        $model->attributes = $filter;

        $oldSourceLanguage = $model->source_language;
        if ($request->isPost && $model->load($request->post())) {
            $client = Clients::findOne(['name' => strtolower($model->client)]);
            $path = Yii::getAlias('@' . $client->name) . '/messages/overrides/';
            $fileName = $model->language . '.' . $model->category . '.override.php';
            $file = $path . $fileName;
            if (is_file($file)) {
                $data = include_once $file;
            }
            unset($data[$oldSourceLanguage]);
            $data[$model->source_language] = $model->translate;
            FileHelper::createDirectory($path);
            $content = '<?php' . PHP_EOL . PHP_EOL . 'return ' . VarDumper::export($data) . ';' . PHP_EOL;
            file_put_contents($file, $content, LOCK_EX);
            Yii::$app->cache->delete('overrides');
            $overridesModel = new OverridesModel();
            $overridesModel->edit($model->category, $model->source_language, $model->translate, $model->language, $client->id, 1);
            return $this->redirect(['index']);
        }

        $language = Languages::findOne(['code' => $filter['language']]);
        $languageShow = $language->title . ' [' . $language->code . ']';

        return $this->render('create', [
            'model' => $model,
            'languageShow' => $languageShow,
            'clientShow' => $filter['client']
        ]);
    }

    /**
     * 删除文本替换
     */
    public function actionDelete()
    {
        $ids = Yii::$app->request->post('ids');
        $overrides = Yii::$app->cache->get('overrides');
        foreach ($overrides as $item) {
            if (in_array($item['id'], $ids)) {
                $path = Yii::getAlias('@' . strtolower($item['client'])) . '/messages/overrides/';
                $fileName = $item['language'] . '.' . $item['category'] . '.override.php';
                $file = $path . $fileName;
                if (is_file($file)) {
                    $data = include $file;
                    unset($data[$item['key']]);
                    if (empty($data)) {
                        FileHelper::unlink($file);
                    } else {
                        $content = '<?php' . PHP_EOL . PHP_EOL . 'return ' . VarDumper::export($data) . ';' . PHP_EOL;
                        file_put_contents($file, $content, LOCK_EX);
                    }
                    $client = Clients::findOne(['name' => strtolower($item['client'])]);
                    $override = OverridesModel::findOne([
                        'client_id' => $client->id,
                        'override_key' => $item['key'],
                        'category' => $item['category'],
                        'language' => $item['language']
                    ]);
                    if ($override) {
                        $override->delete();
                    }
                }
                $emptyDirs = FileHelper::findDirectories($path, ['filter' => function ($path) {
                    $files = FileHelper::findFiles($path);
                    return count($files) == 0 ? true : false;
                }]);

                if (!empty($emptyDirs)) {
                    foreach ($emptyDirs as $dir) {
                        FileHelper::removeDirectory($dir);
                    }
                }
            }
        }
        Yii::$app->cache->delete('overrides');
        return $this->redirect(['index']);
    }

}
